package gfyx_crm_config

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	"gorm.io/gorm"
)

type gfyxCrmConfigRepos struct {
	tenant_db.TenantDB
}

func NewGfyxCrmConfigRepos() GfyxCrmConfigRepositoryIface {
	return &gfyxCrmConfigRepos{}
}

func (g *gfyxCrmConfigRepos) Query(ctx context.Context, condition map[string]interface{}, pageInfo *utils.PageInfo) (int64, []*GfyxCrmConfigPo, error) {
	var result []*GfyxCrmConfigPo
	var count int64
	db := g.GetTenantDB(ctx).Table(GfyxCrmConfigPo{}.TableName()).Where(condition)

	err := db.Count(&count).Error
	if err != nil {
		return 0, nil, err
	}

	if pageInfo != nil && pageInfo.PageSize > 0 && pageInfo.Page > 0 {
		db = db.Offset((pageInfo.Page - 1) * pageInfo.PageSize).Limit(pageInfo.PageSize)
	}

	err = db.Find(&result).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return 0, result, nil
		}
		return 0, nil, err
	}
	return count, result, nil
}
